package store

import (
	"fmt"
	"web/actions"
	"github.com/wuhuang26/locstor"
	"marwan.io/vstore"
)

type State struct {
	User    UserState
	NavBar  NavBarState
}

var localStore = locstor.NewDataStore(locstor.JSONEncoding)
var globalStore vstore.Store
var dialogStore vstore.Store

func Get() vstore.Store {
	if globalStore == nil {
		globalStore = vstore.New(newState())
	}
	return globalStore
}

func GetDialog() vstore.Store {
	if dialogStore == nil {
		dialogStore = vstore.New(newDialogState())
	}
	return dialogStore
}

func GetState() *State {
	return Get().State().(*State)
}

func GetDialogState() *DialogState {
	return GetDialog().State().(*DialogState)
}

func (s *DialogState) Reduce(action interface{}) {
	switch a := action.(type) {
	case *actions.ShowDialog:
		s.Show = true
		s.Title = a.Title
		s.Child = a.Child
		s.OnOk = a.OnOk
		s.OnCancel = a.OnCancel
		s.NoCancelBtn = a.NoCancelBtn

	case *actions.HideDialog:
		s.Show = false
		s.Child = nil
		s.Waiting = false
		s.ErrMsg = ""

	case *actions.SetDialogWaiting:
		if a.Value {
			s.ErrMsg = ""
		}
		s.Waiting = a.Value

	case *actions.SetDialogErrMsg:
		s.ErrMsg = a.Value
	}
}

func newDialogState() *DialogState {
	return &DialogState{}
}

func newState() *State {
	s := &State{}

	return s
}

func (s *State) Reduce(action interface{}) {
	switch a := action.(type) {

	case *actions.Logout:
		fmt.Println(a)
	}
}

type UserState struct {
	Name     string
	LoggedIn bool
}

type DialogState struct {
	Show        bool
	Title       string
	Child       actions.DialogChild
	Waiting     bool
	ErrMsg      string
	OnOk        actions.OnOkFunc
	OnCancel    func()
	NoCancelBtn bool
}

type NavBarState struct {
	ActiveRoute string
}
